﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace UI.Admin.Login
{
    /// <summary>
    /// AjaxAction 的摘要说明
    /// </summary>
    public class AjaxAction : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string dowhat = context.Request["dowhat"];
            if (dowhat == null) dowhat = "";
            string userip = "1213";
            if (dowhat.Equals("login"))
            {
                string delim = "  ";
                string Name = context.Request["Name"].Trim(delim.ToCharArray());;
                string Password = context.Request["Password"].Trim(delim.ToCharArray());
                string Validation = context.Request["Validation"].ToLower();
                if (Name.Length < 1 && Password.Length > 0)
                {
                    context.Response.Write("*请输入用户名");
                    return;
                }
                else if (Password.Length < 1 && Name.Length > 0)
                {
                    context.Response.Write("*请输入密码");
                    return;
                }
                else if (Password.Length < 1 && Name.Length < 1)
                {
                    context.Response.Write("*请输入用户名和密码");
                    return;
                }
                else if (Validation != HttpContext.Current.Session["validate_code"].ToString().ToLower())
                {
                    context.Response.Write("*验证码不正确");
                    return;
                }
                else if (Name.Length > 0 && Password.Length > 0)
                {
                    Models.User user = BLL.Find.FindUser(Name, Password);
                    if (user != null)
                    {
                        Models.Role role = BLL.Find.FindRole(user.RoleID.ToString());
                        HttpContext.Current.Session["user"] = user;
                        HttpContext.Current.Session["role"] = role;
                        HttpContext.Current.Response.Write("success");
                        // 写日志
                        BLL.Create.CreateLogRecord(user.Name, userip, "登录成功");
                    }
                    else
                    {
                        context.Response.Write("*用户名和密码不匹配");
                    }
                    context.Response.End();
                    return;
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}